import 'package:flutter/material.dart';
import 'dart:async';
import 'player_controller.dart';
import 'models/player_state.dart';

class FigoPlayerWidget extends StatefulWidget {
  final FigoPlayerController controller;
  final String? filePath;
  final Widget? placeholder;
  final BoxFit fit;
  final bool showControls;
  final Duration controlsTimeout;
  
  const FigoPlayerWidget({
    Key? key,
    required this.controller,
    this.filePath,
    this.placeholder,
    this.fit = BoxFit.contain,
    this.showControls = true,
    this.controlsTimeout = const Duration(seconds: 3),
  }) : super(key: key);
  
  @override
  _FigoPlayerWidgetState createState() => _FigoPlayerWidgetState();
}

class _FigoPlayerWidgetState extends State<FigoPlayerWidget> {
  bool _showControls = true;
  Timer? _controlsTimer;
  
  @override
  void initState() {
    super.initState();
    if (widget.filePath != null) {
      widget.controller.loadMedia(widget.filePath!);
    }
    _setupControllerListeners();
  }
  
  void _setupControllerListeners() {
    widget.controller.stateStream.listen((state) {
      if (mounted) {
        setState(() {});
      }
    });
    
    widget.controller.errorStream.listen((error) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('播放错误: $error')),
        );
      }
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _toggleControls,
      child: Container(
        color: Colors.black,
        child: Stack(
          children: [
            // 视频显示区域
            _buildVideoArea(),
            // 控制面板
            if (_showControls && widget.showControls)
              _buildControls(),
            // 加载指示器
            if (widget.controller.state == PlayerState.loading)
              _buildLoadingIndicator(),
          ],
        ),
      ),
    );
  }
  
  Widget _buildVideoArea() {
    return Center(
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: Container(
          color: Colors.black,
          child: widget.placeholder ?? const Center(
            child: Text(
              '视频播放区域',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ),
      ),
    );
  }
  
  Widget _buildControls() {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        height: 100,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.transparent, Colors.black54],
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            IconButton(
              icon: Icon(widget.controller.isPlaying ? Icons.pause : Icons.play_arrow),
              onPressed: _togglePlayPause,
              color: Colors.white,
            ),
            IconButton(
              icon: const Icon(Icons.stop),
              onPressed: _stop,
              color: Colors.white,
            ),
            IconButton(
              icon: const Icon(Icons.volume_up),
              onPressed: _showVolumeDialog,
              color: Colors.white,
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildLoadingIndicator() {
    return const Center(
      child: CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
      ),
    );
  }
  
  void _toggleControls() {
    setState(() {
      _showControls = !_showControls;
    });
    
    if (_showControls) {
      _startControlsTimer();
    }
  }
  
  void _startControlsTimer() {
    _controlsTimer?.cancel();
    _controlsTimer = Timer(widget.controlsTimeout, () {
      if (mounted) {
        setState(() {
          _showControls = false;
        });
      }
    });
  }
  
  void _togglePlayPause() {
    if (widget.controller.isPlaying) {
      widget.controller.pause();
    } else {
      widget.controller.play();
    }
  }
  
  void _stop() {
    widget.controller.stop();
  }
  
  void _showVolumeDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('音量控制'),
        content: StatefulBuilder(
          builder: (context, setState) {
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('当前音量: ${(widget.controller.volume * 100).round()}%'),
                Slider(
                  value: widget.controller.volume,
                  onChanged: (value) {
                    setState(() {
                      widget.controller.setVolume(value);
                    });
                  },
                ),
              ],
            );
          },
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
  
  @override
  void dispose() {
    _controlsTimer?.cancel();
    super.dispose();
  }
}
